package org.groupg.practice;

import io.github.resilience4j.retry.Retry;
import io.github.resilience4j.retry.RetryConfig;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;

public class FileIOExample {

    // 带重试的文件读取
    static String readFileWithRetry(String filePath) throws Throwable {
        RetryConfig config = RetryConfig.<String>custom()
                .maxAttempts(3)
                .waitDuration(Duration.ofMillis(500))
                .retryOnResult(a-> a.length() < 10) // 如果结果长度<10 则重试
                .retryOnException(e -> e instanceof IOException) // 仅对IOException重试
                .failAfterMaxAttempts(true) // 重试失败后抛出异常
                .build();

        Retry retry = Retry.of("fileRetry", config);

        // 修复：使用CheckedFunction处理受检异常
        return retry.executeCheckedSupplier(() -> {
            System.out.println("Attempting to read file...");
            return readFile(filePath); // 直接抛出IOException
        });
    }

    // 文件读取逻辑（带模拟故障）
    static String readFile(String filePath) throws IOException {
        Path path = Paths.get(filePath);
        if (!Files.exists(path)) {
            // 模拟首次读取时文件不存在
            if (!Files.exists(Paths.get("force_create.txt"))) {
                throw new IOException("File not found (simulated)");
            }
        }
        return "File content";
    }

    // 回退方法
    static String fallback(Throwable ex) {
        System.err.println("Fallback due to: " + ex.getMessage());
        return "Default content";
    }

    public static void main(String[] args) {
        try {
            String content = readFileWithRetry("test.txt");
            System.out.println("Final result: " + content);
        } catch (Throwable e) {
            System.out.println("Using fallback: " + fallback(e));
        }
    }
}